package com.wyf.cnbeta;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.umeng.analytics.MobclickAgent;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.ArrayList;


public class MainActivity extends AppCompatActivity {
    ListView listView;
    ArrayList<String> newsNameList;
     ArrayList<String> newsHrefList;

    RefreshLayout swipeRefreshLayout;
    ArrayAdapter adapter;
    static  int page=2;




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//                        .setAction("Action", null).show();

              //  new Refresh().execute();
                listView.setSelection(0);
            }
        });


        listView=(ListView)findViewById(R.id.list_view);
        newsNameList=new ArrayList<String>();
        newsHrefList=new ArrayList<String>();


        adapter=new ArrayAdapter(MainActivity.this,android.R.layout.simple_list_item_1,newsNameList);
        listView.setAdapter(adapter);

        swipeRefreshLayout=(RefreshLayout)findViewById(R.id.swipeRefreshLayout);
        swipeRefreshLayout.setColorSchemeResources(R.color.colorAccent);
        //设置刷新监听
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new Refresh().execute();
            }
        });

        swipeRefreshLayout.setOnLoadListener(new RefreshLayout.OnLoadListener() {

            @Override
            public void onLoad() {
                new PullToRefresh().execute();

            }
        });
        //MobclickAgent.onEvent(MainActivity.this,"swipeRefreshLayout");
        //MobclickAgent.onEvent(MainActivity.this,"listView");
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
               // Toast.makeText(MainActivity.this,newsHrefList.get(position),Toast.LENGTH_SHORT).show();

                Intent intent=new Intent(MainActivity.this,NewsActivity.class);
                intent.putExtra("href",newsHrefList.get(position));
                startActivity(intent);
            }
        });


        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
            }
        });
        new Refresh().execute();
        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }




    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
//        if (id == R.id.action_settings) {
//            return true;
//        }
         if(id==R.id.action_about)
         {
             startActivity(new Intent(MainActivity.this,AboutActivity.class));
             return  true;
         }

        return super.onOptionsItemSelected(item);
    }

    /**
     *下拉获取cnBeta第一页数据
     *  @author WYF
     *
     *
     */


    class   Refresh extends AsyncTask{
        String url="http://m.cnbeta.com/wap/index.htm?page=1";

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            swipeRefreshLayout.setRefreshing(true);
        }

        @Override
        protected Object doInBackground(Object[] params) {
            page=2;
            try {
                newsNameList.clear();
                newsHrefList.clear();
                Document doc= Jsoup.connect("http://m.cnbeta.com/wap/index.htm?page=1").get();
                Elements item=doc.getElementsByClass("list");
                for(Element i:item)
                {
                    newsNameList.add(i.select("a").text().toString().trim());
                    newsHrefList.add(i.select("a").attr("abs:href").trim());
                   // Log.d("TAG",""+i.select("a").text().toString().trim()+i.select("a").attr("abs:href").trim());

                }

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;


        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            swipeRefreshLayout.setRefreshing(false);

            adapter=new ArrayAdapter(MainActivity.this,android.R.layout.simple_list_item_1,newsNameList);
            listView.setAdapter(adapter);
        }
    }



    /**
     *拉拉获取cnBeta第N页数据
     *  @author WYF
     *
     *
     */
    class  PullToRefresh extends AsyncTask{


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Object doInBackground(Object[] params) {

            try {

                Document doc= Jsoup.connect("http://m.cnbeta.com/wap/index.htm?page="+page).get();
                Log.d("TAG","http://m.cnbeta.com/wap/index.htm?page=\""+page);
                page++;
                Elements item=doc.getElementsByClass("list");
                for(Element i:item)
                {
                    newsNameList.add(i.select("a").text().toString().trim());
                    newsHrefList.add(i.select("a").attr("abs:href").trim());
                   // Log.d("TAG",""+i.select("a").text().toString().trim()+i.select("a").attr("abs:href").trim());

                }

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }



            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
            adapter.notifyDataSetChanged();
            swipeRefreshLayout.setLoading(false);
        }
    }

}
